﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using IndustrialSmokeCalc.SmokeCalcWCF;

namespace IndustrialSmokeCalc
{
    public partial class AddCompany : PhoneApplicationPage
    {
        private Location loc;
        public AddCompany()
        {
            InitializeComponent();
        }

        private void btnAddCompany_Click(object sender, RoutedEventArgs e)
        {
            SmokeCalcClient client = new SmokeCalcClient();
            client.AddCompanyCompleted += AddCompanyCompleted;
            //client.AddCompanyAsync(listCategory.SelectedValue.ToString(), txtCompanyName.Text, txtCompanyAddress.Text,
            //    txtCompanyCity.Text, txtCompanyProvince.Text, txtCompanyPostal.Text);
            client.AddCompanyAsync("", txtCompanyName.Text, txtCompanyAddress.Text,
                txtCompanyCity.Text, txtCompanyProvince.Text, txtCompanyPostal.Text);
        }

        private void AddCompanyCompleted(object sender, AddCompanyCompletedEventArgs e)
        {
            if (e.Result == "sukses")
            {
                GetCompanyId();
            }
            else
            {
                MessageBox.Show("Nama perusahaan sudah terdaftar pada database." + Environment.NewLine + "Isi dengan nama lain.");
            }
        }

        private void GetCompanyId()
        {
            SmokeCalcClient client = new SmokeCalcClient();
            client.GetCompanyIdCompleted += GetCompanyIdCompleted;
            client.GetCompanyIdAsync(txtCompanyName.Text);
        }

        private void GetCompanyIdCompleted(object sender, GetCompanyIdCompletedEventArgs e)
        {
            DataSingleton.Instance.CompanyId = e.Result;
            NavigationService.Navigate(new Uri("/ChimneyMap.xaml", UriKind.Relative));
        }

        private void btnGetLocation_Click(object sender, RoutedEventArgs e)
        {
            loc = new Location();
            GeoCoordinate geoCoordinate = loc.GetCoordinate();
            double latitude = geoCoordinate.Latitude;
            double longitude = geoCoordinate.Longitude;
            loc.GetAddress(latitude.ToString(), longitude.ToString());
            loc.PropertyChanged += loc_PropertyChanged;
        }

        void loc_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            txtCompanyAddress.Text = loc.Address;
            txtCompanyCity.Text = loc.City;
            txtCompanyProvince.Text = loc.Province;
            txtCompanyPostal.Text = loc.PostalCode;
        }
    }
}